import ImageLayer from 'ol/layer/Image'
import { ImageWMS } from 'ol/source'
import { apiList } from '@/api/apiList'
import useResourceHelper from '../ui/useResourceHelper'
import { ElMessage } from 'element-plus'
import useMapHelper from './useMapHelper'

import { register as proj4Register } from 'ol/proj/proj4'
import { default as proj4 } from 'proj4'
import { Projection } from 'ol/proj'
import ImageSource from 'ol/source/Image'

function useTifSwipeLayer() {
    const tifLayerLeft = new ImageLayer({
        zIndex: 50,
    })
    const tifLayerRight = new ImageLayer({
        zIndex: 50,
    })


    const mapHelper = useMapHelper()

    const resourceHelper = useResourceHelper()

    async function changeTif(path: string, targetLayer: ImageLayer<ImageSource>) {
        const replaced_path = resourceHelper.replaceDiskHeader(path)

        const metaInfo = await apiList.wmsApi.getMetaInfo({
            file: replaced_path,
        })

        if (!metaInfo) {
            ElMessage.warning('获取meta信息失败')
            return undefined
        }

        if (metaInfo.srs) {
            proj4.defs(replaced_path, metaInfo.srs)

            proj4Register(proj4)
        }

        const extent = mapHelper.getImgExtent(metaInfo)

        if (path) {
            const wmsSource = new ImageWMS({
                url: '/map_api/wms',
                
                params: {
                    file: replaced_path,
                    bands: '1,2,3',
                    transparent: true,
                    FORMAT: 'image/png',
                    isEnhance: true,
                    srs: replaced_path,
                },
                projection: replaced_path,
            })


            targetLayer.setSource(wmsSource)

            return {
                extent,
                source: wmsSource,
                metaInfo,
                proj: proj4.Proj(replaced_path),
                projCode: replaced_path,
            }
        }
    }

    return {
        tifLayerLeft,
        tifLayerRight,
        changeTif,
    }
}

export default useTifSwipeLayer
